# -*- coding: utf-8 -*-
from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt
from treeitem import TreeItem

class TreeModel(QAbstractItemModel):
    def __init__(self, data, parent=None):
        super(TreeModel, self).__init__(parent)

        self.rootItem = TreeItem(("Navigator",))
        if data == None:
            self.rootItem.appendChild(('No Table',), self.rootItem)
            # lines = [("No table", ), ]
        else:
            # lines = data
            for item in data:
                self.rootItem.appendChild(TreeItem((item,), self.rootItem))
        # self.setupModelData(lines, self.rootItem)
        # self.setupData(self.rootItem)

    def columnCount(self, parent):
        if parent.isValid():
            return parent.internalPointer().columnCount()
        else:
            return self.rootItem.columnCount()

    def data(self, index, role):
        if not index.isValid():
            return None

        if role != Qt.DisplayRole:
            return None

        item = index.internalPointer()

        return item.data(index.column())

    def flags(self, index):
        if not index.isValid():
            return Qt.NoItemFlags

        return Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def headerData(self, section, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.rootItem.data(section)

        return None

    def index(self, row, column, parent):
        if not self.hasIndex(row, column, parent):
            return QModelIndex()

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        childItem = parentItem.child(row)
        if childItem:
            return self.createIndex(row, column, childItem)
        else:
            return QModelIndex()

    def parent(self, index):
        if not index.isValid():
            return QModelIndex()

        childItem = index.internalPointer()
        parentItem = childItem.parent()

        if parentItem == self.rootItem:
            return QModelIndex()

        return self.createIndex(parentItem.row(), 0, parentItem)

    def rowCount(self, parent):
        if parent.column() > 0:
            return 0

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        return parentItem.childCount()

    def setupModelData(self, lines, parent):
        parents = [parent]

        for line in lines:
            # parents[-1].appendChild(TreeItem(line, parents[-1]))
            parent.appendChild(TreeItem((line,), parent))

    def addData(self, value):
        self.rootItem.appendChild(TreeItem((value,), self.rootItem))
        self.dataChanged.emit()
